﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Utilities;

namespace ManageTicket.Human
{
    public partial class frmDepartment : frmBase
    {
        #region Contructor
        public frmDepartment()
        {
            InitializeComponent();
        }
        #endregion

        #region Variable
        ManageTicket.Library.Control.ExecuteControl exeCtrl;

        //permission
        bool bAdd = false;
        bool bEdit = false;
        bool bDelete = false;
        bool bCancel = false;
        bool bSave = false;
        bool bFunction = false;
        bool bView = false;
        bool bFind = false;
        bool bExport = false;
        bool bSendmail = false;
        bool bPrint = false;

        clsMethod4All objMethod = new clsMethod4All();
        ManageTicket.Library.Common.CommonFunction clsCommonFunc = new ManageTicket.Library.Common.CommonFunction();

        TreeNode SeleteNode;
        string sModel = ""; //Store AND or UPDATE status
        private const string ADD_MODEL = "ADD";
        private const string UPDATE_MODEL = "UPDATE";
        private Business.Department boDept = new Business.Department();
        private ArrayList arrDept = new ArrayList();
        #endregion

        #region Event
        private void frmDepartment_Load(object sender, EventArgs e)
        {
            //execute control
            exeCtrl = new ManageTicket.Library.Control.ExecuteControl();
            exeCtrl.Dock = DockStyle.Fill;
            exeCtrl.lblDescription.Text = "Cập nhật phòng ban";
            pnlExe.Controls.Add(exeCtrl);
 
            //permission
            clsCommonFunc.GetPermission(ref bAdd, ref bEdit, ref bDelete, ref bCancel, ref bSave, ref bFunction, ref bView, ref bFind, ref bExport, ref bSendmail, ref bPrint, frmMain.CurrentUser.UserId, "FORM_12");

            //set status
            LoadStatusOnce();
            LoadStatus(false, false, false, false, false);

            BuildTree();
        }

        private void trwOrg_BeforeSelect(object sender, TreeViewCancelEventArgs e)
        {
            SeleteNode = e.Node;
            sModel = "";
        }

        private void trwOrg_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (SeleteNode == null)
            {
                return;
            }

            TreeNode oSeleteNode = SeleteNode;
            if (oSeleteNode == null)
            {
                txtParentName.Text = "";
                txtDepartmentName.Text = "";
            }
            else
            {
                if (object.ReferenceEquals(oSeleteNode.Tag.GetType(), typeof(DataObjects.Department)))
                {
                    DataObjects.Department oDept = (DataObjects.Department)oSeleteNode.Tag;
                    if (oSeleteNode.Parent == null)
                    {
                        txtParentName.Text = "";
                    }
                    else
                    {
                        txtParentName.Text = oSeleteNode.Parent.Text;
                    }
                    txtDepartmentName.Text = oDept.DepartmentName;
                    txtRemark.Text = oDept.Remark;

                    if (oDept.Status == "CUR")
                    {
                        LoadStatus(true, true, true, false, false);
                    }
                    else 
                    {
                        LoadStatus(false, false, false, false, false);
                    }
                }
            }
            IsEdit();
        }
        #endregion

        #region Execute

        public override void Add()
        {
            txtParentName.Text = SeleteNode.Text;
            txtDepartmentName.Text = "";
            txtRemark.Text = "";

            LoadStatus(false, false, false, true, true);
            sModel = ADD_MODEL;
            IsEdit();
            txtDepartmentName.Focus();
        }

        public override void Edit()
        {
            if( SeleteNode == null)
                return;
            LoadStatus(false, false, false, true, true);
            sModel = UPDATE_MODEL;
            IsEdit();
            txtDepartmentName.Focus();
        }

        public override void Delete()
        {
            try 
            {
                if (SeleteNode == null) 
                {
                    return;
                }
        
                if (MessageBox.Show("Bạn có thực sự muốn xóa?", "Aquarius", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) 
                {
                    if (object.ReferenceEquals(SeleteNode.Tag.GetType(), typeof(DataObjects.Department))) 
                    {
                        TreeNode oSeleteNode = SeleteNode;
                        DataObjects.Department oDept = (DataObjects.Department)oSeleteNode.Tag;
                    
                        if (oDept.DepartmentId == "0") {
                            MessageBox.Show("Không thể xóa nút gốc.", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        else 
                        {
                            //find child dept
                            ArrayList listChildren = default(ArrayList);
                            listChildren = boDept.GetListByParentId(oDept.DepartmentId);
                            
                            if (listChildren.Count > 0) {
                                MessageBox.Show("Nút không rỗng. Bạn không thể xóa.", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                            else {
                                //Check Existing in table
                                //if (this.CheckExitToDelete(oDept.DEPT_CODE)) {
                                //    MessageBox.Show(".", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                //    return;
                                //}
                                
                                //delete
                                boDept.DeleteByPK(oDept.DepartmentId);
                                
                                //Refesh 
                                TreeNode oParent = SeleteNode.Parent;
                                if ((oParent != null)) {
                                    oParent.Nodes.Remove(SeleteNode);
                                }

                                MessageBox.Show("Xóa phòng ban thành công.", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                Cancel();
                            }
                        }
                    }
                }
            }
            catch (Exception ex) {
                MessageBox.Show(ex.Message, "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        public override void Cancel()
        {
            sModel = "";
            txtParentName.Text = "";
            txtDepartmentName.Text = "";
            txtRemark.Text = "";
            LoadStatus(false, false, false, false, false);
            trwOrg_AfterSelect(null, null);
        }

        public override void Save()
        {
            if (CheckValid())
            {
                try
                {
                    if (sModel.Trim().ToUpper().Equals(ADD_MODEL))
                    {
                        AddDept();
                    }
                    else if (sModel.Trim().ToUpper().Equals(UPDATE_MODEL))
                    {
                        UpdateDept();
                    }
                    MessageBox.Show("Cập nhật phòng ban thành công.", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    Cancel();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message + Environment.NewLine + "Không thể cập nhật phòng ban.", "Aquarius Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        #endregion

        #region Method
        
        private void BuildTree()
        {
            trwOrg.Nodes.Clear();
            TreeNode treeNode;
            DataObjects.Department oDept;
            arrDept = boDept.GetListByStatus("CUR");
            ArrayList firstLevelNodes = GetChild();
            for (int i = 0; i <= firstLevelNodes.Count - 1; i++)
            {
                treeNode = BuildSubTree((DataObjects.Department)firstLevelNodes[i]);
                oDept = (DataObjects.Department)firstLevelNodes[i];
                treeNode.Tag = oDept;
                this.trwOrg.Nodes.Add(treeNode);
            }

            this.trwOrg.ImageIndex = 0;
            trwOrg.Nodes[0].Expand();
        }

        private TreeNode BuildSubTree(DataObjects.Department obj)
        {

            TreeNode treeNode = new TreeNode(Convert.ToString(obj.DepartmentName));
            ArrayList childArray = GetChild(obj.DepartmentId);
            TreeNode childNode = default(TreeNode);
            DataObjects.Department oDept;
            for (int i = 0; i <= childArray.Count - 1; i++)
            {
                childNode = BuildSubTree((DataObjects.Department)childArray[i]);
                oDept = (DataObjects.Department)childArray[i];
                childNode.Tag = oDept;
                treeNode.Nodes.Add(childNode);
            }
            return treeNode;

        }

        private ArrayList GetChild()
        {
            ArrayList arr = new ArrayList();
            arr = arrDept;
            ArrayList array = new ArrayList();
            foreach (DataObjects.Department obj in arr)
            {
                if (obj.ParentId == "-1")
                {
                    array.Add(obj);
                }
            }
            return array;

        }

        private ArrayList GetChild(string parentID)
        {
            ArrayList arr = new ArrayList();
            arr = arrDept;
            ArrayList array = new ArrayList();
            foreach (DataObjects.Department obj in arr)
            {
                if (obj.ParentId == parentID)
                {
                    array.Add(obj);
                }
            }
            return array;

        }

        private void LoadStatusOnce()
        {
            exeCtrl.btnFunction.Enabled = false;
            exeCtrl.btnView.Enabled = false;
            exeCtrl.btnFind.Enabled = false;
            exeCtrl.btnExport.Enabled = false;
            exeCtrl.btnSendmail.Enabled = false;
            exeCtrl.btnPrint.Enabled = false;

            exeCtrl.btnFunction.BackColor = Color.FromArgb(171, 171, 171);
            exeCtrl.btnView.ButtonColor = Color.FromArgb(171, 171, 171);
            exeCtrl.btnFind.ButtonColor = Color.FromArgb(171, 171, 171);
            exeCtrl.btnExport.ButtonColor = Color.FromArgb(171, 171, 171);
            exeCtrl.btnSendmail.ButtonColor = Color.FromArgb(171, 171, 171);
            exeCtrl.btnPrint.ButtonColor = Color.FromArgb(171, 171, 171);

            exeCtrl.btnFunction.ForeColor = Color.FromArgb(241, 244, 251);
            exeCtrl.btnView.ForeColor = Color.FromArgb(241, 244, 251);
            exeCtrl.btnFind.ForeColor = Color.FromArgb(241, 244, 251);
            exeCtrl.btnExport.ForeColor = Color.FromArgb(241, 244, 251);
            exeCtrl.btnSendmail.ForeColor = Color.FromArgb(241, 244, 251);
            exeCtrl.btnPrint.ForeColor = Color.FromArgb(241, 244, 251);
        }

        private void LoadStatus(bool blAdd, bool blEdit, bool blDelete, bool blCancel, bool blSave)
        {
            exeCtrl.btnAdd.Enabled = blAdd & bAdd;
            exeCtrl.btnEdit.Enabled = blEdit & bEdit;
            exeCtrl.btnDelete.Enabled = blDelete & bDelete;
            exeCtrl.btnCancel.Enabled = blCancel & bCancel;
            exeCtrl.btnSave.Enabled = blSave & bSave;

            exeCtrl.btnAdd.ButtonColor = exeCtrl.btnAdd.Enabled ? Color.FromArgb(0, 163, 211) : Color.FromArgb(171, 171, 171);
            exeCtrl.btnEdit.ButtonColor = exeCtrl.btnEdit.Enabled ? Color.FromArgb(0, 163, 211) : Color.FromArgb(171, 171, 171);
            exeCtrl.btnDelete.ButtonColor = exeCtrl.btnDelete.Enabled ? Color.FromArgb(0, 163, 211) : Color.FromArgb(171, 171, 171);
            exeCtrl.btnCancel.ButtonColor = exeCtrl.btnCancel.Enabled ? Color.FromArgb(0, 163, 211) : Color.FromArgb(171, 171, 171);
            exeCtrl.btnSave.ButtonColor = exeCtrl.btnSave.Enabled ? Color.FromArgb(0, 163, 211) : Color.FromArgb(171, 171, 171);

            exeCtrl.btnAdd.ForeColor = exeCtrl.btnAdd.Enabled ? Color.FromArgb(0, 0, 0) : Color.FromArgb(241, 244, 251);
            exeCtrl.btnEdit.ForeColor = exeCtrl.btnEdit.Enabled ? Color.FromArgb(0, 0, 0) : Color.FromArgb(241, 244, 251);
            exeCtrl.btnDelete.ForeColor = exeCtrl.btnDelete.Enabled ? Color.FromArgb(0, 0, 0) : Color.FromArgb(241, 244, 251);
            exeCtrl.btnCancel.ForeColor = exeCtrl.btnCancel.Enabled ? Color.FromArgb(0, 0, 0) : Color.FromArgb(241, 244, 251);
            exeCtrl.btnSave.ForeColor = exeCtrl.btnSave.Enabled ? Color.FromArgb(0, 0, 0) : Color.FromArgb(241, 244, 251);
        }

        private void IsEdit()
        {
            if (sModel == ADD_MODEL | sModel == UPDATE_MODEL)
            {
                txtDepartmentName.ReadOnly = false;
                txtRemark.ReadOnly = false;
            }
            else
            {
                txtDepartmentName.ReadOnly = true;
                txtRemark.ReadOnly = true;
            }
        }

        private bool CheckValid()
        {
            if (txtDepartmentName.Text.Trim().Length == 0)
            {
                MessageBox.Show("Vui lòng nhập tên phòng ban.", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtDepartmentName.Focus();
                return false;
            }
            return true;
        }

        private void AddDept()
        {
            if (SeleteNode == null)
            {
                return;
            }
            //check level for node
            if (SeleteNode.FullPath.Split( new char[]{'\\'}).Length == 7)
            {
                MessageBox.Show("Không thể thêm nhánh con được nữa.", "Aquarius Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Cancel();
                return;
            }
            DataObjects.Department oDeptParent;
            if (object.ReferenceEquals(SeleteNode.Tag.GetType(), typeof(DataObjects.Department)))
            {
                oDeptParent = (DataObjects.Department)SeleteNode.Tag;

                //Add new 
                DataObjects.Department oChild = new DataObjects.Department();
                oChild.ParentId = oDeptParent.DepartmentId;
                oChild.DepartmentId = (boDept.GetMaxID() + 1).ToString();
                oChild.DepartmentName = txtDepartmentName.Text;
                oChild.Remark = txtRemark.Text;
                oChild.Status = "CUR";

                //Insert
                boDept.Insert(oChild);

                //Add node to the tree view
                TreeNode oChildNode = new TreeNode(txtDepartmentName.Text, 0, 0);
                oChildNode.Tag = oChild;
                SeleteNode.Nodes.Add(oChildNode);
                
            }
        }

        private void UpdateDept()
        {
            if (SeleteNode == null)
            {
                return;
            }

            object oTag = SeleteNode.Tag;

            if (object.ReferenceEquals(oTag.GetType(), typeof(DataObjects.Department)))
            {
                DataObjects.Department oDept;
                oDept = (DataObjects.Department)oTag;
                oDept.DepartmentName = txtDepartmentName.Text;
                oDept.Remark = txtRemark.Text;
                boDept.Update(oDept);

                SeleteNode.Text = txtDepartmentName.Text;
            }
        }

        #endregion

        
    }
}
